package com.data.modules.smzh.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.data.common.api.vo.Result;
import com.data.common.util.AesUtil;
import com.data.common.util.JwtIOTAuthUtil;
import com.data.common.util.KamliClientUtil;
import com.data.common.util.RedisUtil;
import com.data.modules.smzh.entity.*;
import com.data.modules.smzh.mapper.RegisterMapper;
import com.data.modules.smzh.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: register
 * @Author: data-boot
 * @Date:   2022-12-08
 * @Version: V1.0
 */
@Service
public class RegisterServiceImpl extends ServiceImpl<RegisterMapper, Register> implements IRegisterService {


    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISmUserService userService;
    @Autowired
    private IRegisterappuserService registerAppUser;
    @Autowired
    private IBuildinguserService buildinguserService;
    @Autowired
    private IBuildingService buildingService;
    @Autowired
    private IProjectService projectService;


    @Override
    @Transactional
    public void saveRegisterInfo(Register register) {


    }

    @Override
    @Transactional
    public Result saveRegisterInfo(String mobile, String passWord) {

        Result<String> result = new Result<String>();
        Register register = null;
        String str = "";
        String realPassWord = "";
        try {
            //先加密 待上线 注释掉
            passWord = AesUtil.aesEncrypt(passWord);

            str = AesUtil.aesDecryption(passWord);

            realPassWord = AesUtil.dbAesEncrypt(str);

            register = new Register();
            register.setMobile(mobile);
            register.setNick("nick_"+mobile);
            register.setCreateTime(new Date());
            register.setPassword(realPassWord);

        } catch (Exception e) {

            result.setCode(10001);
            result.setMessage("failed");
            result.setSuccess(false);
            result.setResult(e.getMessage());

        }

        try {
            this.save(register);

            redisUtil.del(mobile);
        } catch (Exception e) {
            result.setCode(10003);
            result.setMessage("号码已存在");
            result.setSuccess(false);
        }
        //SIP账号放号：
        if(!KamliClientUtil.doPost(String.valueOf(register.getId()),str)){
            return Result.error("通知kamilis 失败！");
        };
        return  result;
    }

    /**
     * app 登录 校验密码 获取用户相关信息
     * @param mobile
     * @param passWord
     * @return
     */
    @Override
    @Transactional
    public Result<Object> getRegisterInfo(String mobile, String passWord) {

        Result<Object> result = new Result<Object>();
        Map<String,Object> map = new HashMap<>();
        List<Map> userAppbind = new ArrayList<>();
        String str = "";
        String realPassWord = "";
        List<Register> list = this.lambdaQuery().eq(Register::getMobile,mobile).list();

        if(ObjectUtil.isEmpty(list)){
            result.setCode(10010);
            result.setSuccess(false);
            result.setMessage("手机号不存在，请核实手机号");
        }

        try {

            Register register = list.get(0);
            //先加密 待上线 注释掉
            passWord = AesUtil.aesEncrypt(passWord);

            str = AesUtil.aesDecryption(passWord);
            realPassWord = AesUtil.dbAesEncrypt(str);

            if(ObjectUtil.equals(register.getPassword(),realPassWord)){
                //通过手机号查询用户基本信息
                List<SmUser> smUserslist = userService.lambdaQuery().eq(SmUser::getPersonCode,mobile).list();

                if(ObjectUtil.isNotEmpty(smUserslist)){
                    SmUser smUser = smUserslist.get(0);

                    //先查询 没有在新增
                    int i = registerAppUser.lambdaQuery().eq(Registerappuser::getRegisterId,register.getId())
                            .eq(Registerappuser::getUserId,smUser.getId())
                            .eq(Registerappuser::getAppId,smUser.getAppId())
                            .list().size();

                    if(i == 0){

                        Registerappuser registerappuser = new Registerappuser();
                        registerappuser.setAppId(smUser.getAppId());
                        registerappuser.setUserId(smUser.getId());
                        registerappuser.setRegisterId(register.getId());

                        registerAppUser.save(registerappuser);
                    }

                    //查询绑定的建筑信息
                    List<Buildinguser> uniqueNoList = buildinguserService.lambdaQuery().eq(Buildinguser::getUserId,smUser.getId()).list();

                    if(ObjectUtil.isNotEmpty(uniqueNoList)){
                        userAppbind = uniqueNoList.stream().map(x->{
                        Map<String,Object> map1 = new HashMap();
                            map1.put("username",x.getUniqueNo());
                            map1.put("bindusername",register.getId());
                        return  map1;

                        }).collect(Collectors.toList());
                    }

                    List<String> fileIds = uniqueNoList.stream().map(x->x.getUniqueNo()).collect(Collectors.toList());

                    List<Building> buildingList = buildingService.lambdaQuery().in(Building::getUniqueNo, fileIds).list();

                    //生成token
                    String token = JwtIOTAuthUtil.sign(mobile,register.getId().toString());

                    //建筑信息
                    map.put("building",buildingList);
                    //同步 kamil  账号  绑定账号
                    KamliClientUtil.doPostBindUserUrlList(userAppbind);

                    List projectList = projectService.lambdaQuery().eq(Project::getAppId,smUser.getAppId()).list();
                    //获取token
                    map.put("project",projectList);
                    map.put("accountID",register.getId());
                    map.put("token",token);
                }

                result.setResult(map);

            }else{
                result.setCode(10010);
                result.setSuccess(false);
                result.setMessage("密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 重置密码
     * @param mobile
     * @param passWord
     * @return
     */
    @Override
    public Result<?> resetPassword(String mobile, String passWord) {
        Result<String> result = new Result<String>();
        String str = "";
        String realPassWord = "";

        try {
            //先加密 待上线 注释掉
            passWord = AesUtil.aesEncrypt(passWord);

            str = AesUtil.aesDecryption(passWord);
            realPassWord = AesUtil.dbAesEncrypt(str);

            Register register = this.lambdaQuery().eq(Register::getMobile,mobile).one();
            if(ObjectUtil.isNotEmpty(register)){

                register.setPassword(realPassWord);
                this.updateById(register);
                //更新 sip  密码
                KamliClientUtil.doPostRestPwdUr(String.valueOf(register.getId()),str);

                redisUtil.del(mobile);

            }else{
                result.setMessage("手机号不正确");
                result.setCode(10002);
                result.setSuccess(false);
                return result;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
